<?php
namespace frontend\modules\Oauth\services;

use Yii;
use common\models\GuardPartner;
use yii\base\Exception;

/**
 * Class OauthService
 * @package frontend\modules\Oauth\Services
 */
class OauthService
{
    /**
     * @var $partner array
     * 合作业务方数据
     */
    protected static $partner ;

    /**
     * @var array
     * 支持回调域名白名单设置
     */
    protected static $whiteHostMap = [
        'changziming-guard-frontend.test.kanongyun.com',
    ];

    /**
     * @param $clientId
     * @return \frontend\modules\Oauth\base\AbstractOauth
     * @throws
     * 根据clientId 获取实例
     */
    public static function getInstance($clientId)
    {
        $partner = GuardPartner::find()->where([
            'client_id' => $clientId,
            'status'    => 1
        ])->limit(1)->asArray()->one();
        if(!$partner) {
            throw new Exception('不被识别的业务标识');
        }
        self::$partner = $partner;
        // platform 根据平台获取不同处理类
        $platForm = ucfirst(strtolower($partner['platform']));
        $oauthModel = 'frontend\modules\Oauth\extras\\'.$platForm.'Oauth' ;
        $obj = Yii::createObject([
            'class' => $oauthModel,
        ]);
        /** @var $obj \frontend\modules\Oauth\base\AbstractOauth */
        return $obj;
    }

    /**
     * @return array
     * 获取合作方数据
     */
    public static function getPartner()
    {
        return self::$partner;
    }

    /**
     * @param $url
     * @return bool
     * 白名单域名检测
     */
    public static function checkWhite($url)
    {
        $urlInfo = parse_url($url);
        if(!$urlInfo) return false ;
        $host = $urlInfo['host'];
        if(in_array($host,self::$whiteHostMap)){
            return true ;
        }else{
            return false ;
        }
    }

    /**
     * @param $key
     * @param $value
     * @param int $expireTime
     * @throws \yii\base\InvalidConfigException
     */
    public static function setCache($key,$value,$expireTime=120)
    {
        $redis  = Yii::$app->get('redis');
        $redis->select(5);
        $redis->setex('oauth:'.$key,$expireTime,$value);
    }

    /**
     * @param $key
     * @return mixed
     * @throws \yii\base\InvalidConfigException
     */
    public static function getCache($key)
    {
        $redis  = Yii::$app->get('redis');
        $redis->select(5);
        $data   = $redis->get('oauth:'.$key);
        return $data;
    }
}